package com.socket;

import com.alibaba.fastjson.JSON;
import com.commons.SpringUtil;
import com.model.DanmakuShield;
import com.server.DanmakuShieldService;
import com.server.impl.DanmakuShieldServicelmpl;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/logic/ws/DanmakuCount")
@Component
public class DanmakuShieldWS {
    private static DanmakuShieldService service = SpringUtil.getBean(DanmakuShieldServicelmpl.class);

    private static int onlineCount = 0;

    private static CopyOnWriteArraySet<DanmakuShieldWS> wsSet = new CopyOnWriteArraySet<>();

    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        wsSet.add(this);
        addOnlineCount();
    }

    @OnClose
    public void onClose(){
        wsSet.remove(this);
        subOnlineCount();
    }

    @OnMessage
    public void onMessage(String message, Session session) throws IOException{
        List<DanmakuShield> result = null;
        if (message != null && !"".equals(message)){
            int top = Integer.parseInt(message);
            result = service.getAllDanmakuShield();
        } else {
            result = service.getAllDanmakuShield();
        }
        session.getBasicRemote().sendText(JSON.toJSONString(result));
    }

    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("有错误发生");
        error.printStackTrace();
    }


    public static void sendInfo() throws IOException{
        List<DanmakuShield> result = service.getAllDanmakuShield();
        for (DanmakuShieldWS item : wsSet){
            try{
                item.session.getBasicRemote().sendText(JSON.toJSONString(result));
            }catch (IOException e){
                continue;
            }
        }
    }

    private static void subOnlineCount(){
        if(onlineCount > 0)
            onlineCount --;
    }

    private static void addOnlineCount(){onlineCount ++;}

}
